﻿using Custom.Framework;
using Custom.Model.Entity;
using Custom.Service.Repository;
using Maticsoft.DBUtility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TransferTool
{
    public partial class Form1 : Form
    {
        List<CustomInfo> customs = new List<CustomInfo>();
        List<HealthInfo> healths = new List<HealthInfo>();
        List<SaleInfo> sales = new List<SaleInfo>();

        private CustomInfoRepository customBll = new CustomInfoRepository();
        private HealthInfoRepository healthBll = new HealthInfoRepository();
        private SaleInfoRepository saleBll = new SaleInfoRepository();
        private SaleDetailRepository saleDetailBll = new SaleDetailRepository();

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                this.transferCustomTable();
                this.transferHealthTable();
                this.transferSaleInfo();

                MessageBox.Show("操作完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void transferCustomTable()
        {
            string sql1 = "select * from t_huiyuan order by id";

            DataTable dt1 = DbHelperSQL.Query(sql1).Tables[0];
            string content = "正在迁移客户数据，当前进度：";
            if (dt1 != null && dt1.Rows.Count > 0)
            {
                //foreach (DataRow r in dt1.Rows)
                for(int i = 0; i < dt1.Rows.Count; i++)
                {
                    DataRow r = dt1.Rows[i];
                    CustomInfo c = new CustomInfo()
                    {
                        oldid = int.Parse(r["id"].ToString()),
                        cardno = r["hykh"].ToString(),
                        level = r["hyjb"].ToString() == "1级" ? "1" : "2",
                        cusname = r["hyxm"].ToString(),
                        sex = r["hyxb"].ToString() == "男" ? "0" : "1",
                        identityno = r["sfzh"].ToString(),
                        birthday = r["csrq"].ToString(),
                        address = r["jtzz"].ToString(),
                        mobile = r["yddh"].ToString(),
                        qq = r["qq"].ToString(),
                        email = r["email"].ToString(),
                        memo = r["memo"].ToString(),
                        createman = "admin",
                        createtime = DateTime.Parse(r["cjsj"].ToString())
                    };
                    customBll.Insert(c);

                    this.label1.Text = $"正在迁移客户数据（{i} / {dt1.Rows.Count}），，当前进度：" + Math.Round(((double)i / (double)dt1.Rows.Count) * 100, 4).ToString() + "%";
                    Application.DoEvents();
                }
            }
        }

        private int getCusid(int oldid)
        {
            return (int)customBll.Get(w => w.oldid == oldid)?.FirstOrDefault()?.id;
        }

        private void transferHealthTable()
        {
            string sql1 = "select * from t_health order by id";

            DataTable dt1 = DbHelperSQL.Query(sql1).Tables[0];

            string content = "正在迁移健康数据，当前进度：";

            if (dt1 != null && dt1.Rows.Count > 0)
            {
                //foreach (DataRow r in dt1.Rows)
                for(int i = 0; i < dt1.Rows.Count; i++)
                {
                    DataRow r = dt1.Rows[i];
                    HealthInfo h = new HealthInfo();
                    h.cusid = this.getCusid(int.Parse(r["hyid"].ToString()));
                    h.refractionR = r["qg2"].ToString();
                    h.astigmiaR = r["sg2"].ToString();
                    h.axialR = r["zw2"].ToString();
                    h.correctR = r["jz2"].ToString();
                    h.refractionL = r["qg1"].ToString();
                    h.astigmiaL = r["sg1"].ToString();
                    h.axialL = r["zw1"].ToString();
                    h.correctL = r["jz1"].ToString();
                    //h.distance = decimal.Parse(r["tj"].ToString());
                    h.createman = "admin";
                    h.createtime = DateTime.Parse(r["cjsj"].ToString());
                    healthBll.Insert(h);

                    this.label1.Text = $"正在迁移健康数据（{i} / {dt1.Rows.Count}），，当前进度：" + Math.Round(((double)i / (double)dt1.Rows.Count) * 100, 4).ToString() + "%";
                    Application.DoEvents();
                }
            }
        }

        private void transferSaleInfo()
        {
            string sql1 = "select * from t_xiaoshou order by id";

            DataTable dt1 = DbHelperSQL.Query(sql1).Tables[0];

            if (dt1 != null && dt1.Rows.Count > 0)
            {
                //foreach (DataRow r in dt1.Rows)
                for(int i = 0; i < dt1.Rows.Count; i++)
                {                    
                    DataRow r = dt1.Rows[i];
                    try
                    {
                        SaleInfo h = new SaleInfo();
                        h.id = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                        h.cusid = this.getCusid(int.Parse(r["hyid"].ToString()));
                        h.cusname = r["hyxm"]?.ToString();
                        h.cardno = r["hykh"]?.ToString();
                        h.identityno = r["sfzh"]?.ToString();
                        h.mobile = r["yddh"]?.ToString();
                        h.totalamount = decimal.Parse(r["xsje"].ToString());
                        h.createman = "admin";
                        h.createtime = DateTime.Parse(r["xssj"].ToString());
                        saleBll.Insert(h);

                        string sql2 = $"select * from t_xiaoshou_mingxi where xsid = '{r["id"]}' order by id";
                        DataTable dt2 = DbHelperSQL.Query(sql2).Tables[0];
                        if (dt2 != null && dt2.Rows.Count > 0)
                        {
                            foreach (DataRow rr in dt2.Rows)
                            {
                                SaleDetail d = new SaleDetail();
                                d.saleid = h.id;
                                d.name = rr["wpmc"]?.ToString();
                                d.price = decimal.Parse(rr["wpdj"].ToString());
                                d.quantity = decimal.Parse(rr["gmsl"].ToString());
                                d.amount = decimal.Parse(rr["wpje"].ToString());
                                saleDetailBll.Insert(d);
                            }
                        }

                        Logger.Info($"正在迁移销售数据 -- {r["id"]} -- （{i} / {dt1.Rows.Count}），当前进度：" + Math.Round(((double)i / (double)dt1.Rows.Count) * 100, 4).ToString() + "%");

                        this.label1.Text = $"正在迁移销售数据（{i} / {dt1.Rows.Count}），当前进度：" + Math.Round(((double)i / (double)dt1.Rows.Count) * 100, 4).ToString() + "%";
                        Application.DoEvents();
                    }
                    catch (Exception ex)
                    {
                        Logger.Error($"出错id = {r["id"].ToString()}，错误内容：" + ex.Message);
                    }
                }

            
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                customBll.ExecuteSql("delete from custominfo where createtime < '2025-04-01'");
                healthBll.ExecuteSql("delete from healthinfo where createtime < '2025-04-01'");
                saleDetailBll.ExecuteSql("delete from saledetail where saleid in(select id from saleinfo where createtime < '2025-04-01')");           
                saleBll.ExecuteSql("delete from saleinfo where createtime < '2025-04-01'");

                MessageBox.Show("操作完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
